package com.frxuexi.docments

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.docments.entity.DocEntity
import com.frxuexi.lib_base.MyTitleBar
import com.frxuexi.lib_base.RequestType
import com.frxuexi.lib_base.RouterPath
import com.frxuexi.lib_base.UiState
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@Composable
fun DocPage(navHostController: NavHostController, vm: DocViewModel = hiltViewModel()) {
    var list = remember {
        SnapshotStateList<DocEntity>()
    }
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        if (it.type == RequestType.DEFAULT) {
                            Log.i("===", it.data.toString())
                            list.clear()
                            list.addAll(it.data as Collection<DocEntity>)
                        } else if (it.type == RequestType.DELETE) {
                            ToastUtils.showLong("删除成功")
                            list.clear()
                            vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", 1))))
                        }
                    }

                    is UiState.onError -> {
                        Log.i("===", it.msg)
                    }

                    else -> {}
                }
            }
        }

        vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", 1))))
    })

    Scaffold(floatingActionButton = {
        Image(
            painter = painterResource(id = R.drawable.ic_action_add), contentDescription = "",
            modifier = Modifier.size(36.dp)
                .clickable {
                    navHostController.navigate(RouterPath.LOCAL_PAGE)
                }
        )
    }) {
        Column(Modifier.padding(it)) {
            MyTitleBar(title = "文件", navHostController = navHostController)
            LazyColumn(
                Modifier.padding(10.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
                content = {
                    items(list) {
                        DocItem(it, vm)
                    }
                })
        }
    }

}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DocItem(entity: DocEntity, vm: DocViewModel) {
    var isShow by remember {
        mutableStateOf(false)
    }
    Row(modifier = Modifier.combinedClickable(onClick = {
        ToastUtils.showLong(entity.fileName)
    }, onLongClick = {
        isShow = true
    }, onDoubleClick = {
        ToastUtils.showLong(entity.fileName + "双击了")
    })) {
        AsyncImage(
            model = entity.filePath,
            contentScale = ContentScale.Crop,
            contentDescription = "",
            modifier = Modifier
                .size(60.dp)
                .clip(
                    RoundedCornerShape(20.dp)
                )
        )

        Spacer(modifier = Modifier.width(10.dp))
        Column(modifier = Modifier.height(60.dp), verticalArrangement = Arrangement.SpaceBetween) {
            val name = entity.fileName.split(".")[0]
            Text(text = name)
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.fileTime)
            Text(text = time)
        }
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            Text(text = "确认", Modifier.clickable {
                vm.sendIntent(DocIntent.deleteDoc(entity.fileId))//发起删除意图
                isShow = false
            })
        }, dismissButton = {
            Text(text = "取消", Modifier.clickable {
                isShow = false
            })
        }, title = {
            Text(text = "删除")
        }, text = {
            Text(text = "是否删除${entity.fileName} 吗？")
        })
    }
}